<template>
  <!-- 排产 -->
  <el-dialog v-model="visible" title="排产" destroy-on-close width="75%">
    <el-form
      :model="form"
      :rules="rules"
      ref="dialogForm"
      label-width="auto"
      label-position="right"
    >
      <el-form-item label="" style="width: 100%">
        <el-table
          ref="table"
          :data="productList"
          row-key="id"
          @selection-change="handleSelection"
          stripe
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            prop="contractName"
            label="合同名称"
            min-width="100"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="产品名称"
            min-width="100"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="材质"
            prop="vproductMaterial"
            min-width="100"
          ></el-table-column>
          <el-table-column
            label="备注"
            prop="vproductRemark"
            min-width="100"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column prop="num" label="应排产数量" width="100">
            <template #default="scope">
              <p>{{ scope.row.num - scope.row.scheduledNum }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="schedulingNum" label="生产设备" width="200">
            <template #default="scope">
              <el-select
                v-model="scope.row.equipmentId"
                placeholder="请选择设备"
                clearable
                :disabled="scope.row.sonSonList.length != 0"
                style="width: 100%"
                @visible-change="showSelect"
              >
                <el-option
                  v-for="item in equipmentList"
                  :key="item.id"
                  :label="item.equipmentCode"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="schedulingNum" label="排产数量" width="180">
            <template #default="scope">
              <el-input-number
                :precision="0"
                v-model.number="scope.row.schedulingNum"
                placeholder="请输入数量"
                @change="changeNum($event, scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="schedulingNum"
            label="预计完成时间"
            width="300"
          >
            <template #default="scope">
              <div class="rowTime">
                <el-input-number
                  :precision="0"
                  v-model.number="scope.row.hour"
                  placeholder="请输入小时"
                  :disabled="scope.row.sonSonList.length != 0"
                ></el-input-number>
                <p>:</p>
                <el-input-number
                  :precision="0"
                  v-model.number="scope.row.minute"
                  :max="60"
                  placeholder="请输入分钟"
                  :disabled="scope.row.sonSonList.length != 0"
                ></el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" width="80">
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="100"
          >
            <template #default="scope">
              <el-button
                text
                type="primary"
                size="small"
                @click="handleDisassemble(scope.row, scope.$index)"
                >拆解</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submmit()" :loading="isSaveing"
        >确 定</el-button
      >
    </template>

    <el-dialog
      width="60%"
      title="拆解排产"
      v-model="innerVisible"
      append-to-body
    >
      <sc-form-table
        ref="innerTable"
        :modelValue="disassembleProductList"
        :addTemplate="productsTemplate"
      >
        <el-table-column prop="productName" label="产品名称" min-width="100">
        </el-table-column>
        <el-table-column prop="name" label="拆解件名称" min-width="100">
          <template #default="scope">
            <el-input v-model="scope.row.name" placeholder="请输入拆解件名称" />
          </template>
        </el-table-column>
        <el-table-column prop="equipmentId" label="生产设备" width="200">
          <template #default="scope">
            <el-select
              v-model="scope.row.equipmentId"
              placeholder="请选择设备"
              clearable
              style="width: 100%"
              @visible-change="showSelect"
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentCode"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingNum" label="排产数量" width="180">
          <template #default="scope">
            <el-input-number
              :precision="0"
              v-model.number="scope.row.schedulingNum"
              placeholder="请输入数量"
              0
              @change="changeNum($event, scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingNum" label="预计完成时间" width="300">
          <template #default="scope">
            <div class="rowTime">
              <el-input-number
                :precision="0"
                v-model.number="scope.row.hour"
                placeholder="请输入小时"
              ></el-input-number>
              <p>:</p>
              <el-input-number
                :precision="0"
                v-model.number="scope.row.minute"
                :max="60"
                placeholder="请输入分钟"
              ></el-input-number>
            </div>
          </template>
        </el-table-column>
      </sc-form-table>
      <template #footer>
        <!-- <el-button @click="innerVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="setDisassembleData">确 定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>
<script>
export default {
  emits: ['success'],
  name: 'production',
  data () {
    return {
      visible: false,
      innerVisible: false,
      form: {
        // equipmentId: '',
        produceId: '',
        // estimateFinishTime: '',
        // startTime: this.$TOOL.dateFormat(new Date()),
        schedulingSonList: []
      },
      productList: [],
      equipmentList: [],
      selectionList: [],//被选择的产品
      source: null,//来源 0合同 1退货
      isSaveing: false,
      disassembleProductList: [],//拆解产品
      //拆解产品模版
      productsTemplate: {
        id: '',
        productName: '',
        name: '',
        equipmentId: '',
        schedulingNum: '',
        // finishHour: 0,
        hour: 0,
        minute: 0
      },
      rules: {
        equipmentId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        estimateFinishTime: [
          { type: 'date', required: true, message: '请选择预计完成时间', trigger: 'change' }
        ],
      }
    }
  },
  mounted () {

  },
  methods: {
    open (data) {
      this.visible = true
      this.source = data[0].source
      let ids = data.map(item => item.id).join(',')
      this.form.produceId = ids
      this.getProduceListByIds(ids)
      // this.getList()
    },

    showSelect (val) {
      if (val) {
        this.getList()
      }

    },
    // 获取空闲设备
    async getList () {
      // type: 0//设备状态：0空闲1生产中
      let { data } = await this.$API.produce.equipment.getEquipmentList.get({ type: 0 })
      this.equipmentList = data
    },

    // 获取生产单详情
    async getProduceListByIds (ids) {
      let res = await this.$API.produce.getProduceListByIds.get({ ids })
      let list = res.data || []
      let p_list = []
      list.forEach(item => {
        item.produceProducts.forEach(i_item => {
          i_item.contractName = item.contractName
          i_item.schedulingNum = i_item.num - i_item.scheduledNum
          i_item.equipmentId = ''
          i_item.hour = 0
          i_item.minute = 0
          // i_item.finishHour = 0
          i_item.sonSonList = []
          p_list.push(i_item)
        })
      })
      this.productList = []
      p_list.map((item, index) => {
        if (item.num != item.scheduledNum) {
          this.productList.push(item)
        }
      })
      // this.productList = p_list
    },
    // 产品拆解排产
    handleDisassemble (row) {
      console.log(row)
      this.innerVisible = true
      this.productsTemplate.productName = row.name
      this.productsTemplate.id = row.id
      this.productsTemplate.schedulingNum = row.schedulingNum
      if (row.sonSonList.length == 0) {
        this.disassembleProductList = []
        let template = {
          productName: row.name,
          id: row.id,
          name: '',
          equipmentId: '',
          schedulingNum: row.schedulingNum,
          hour: 0,
          minute: 0,
          // finishHour: 0,
        }
        this.disassembleProductList.push(template)

      } else {
        this.disassembleProductList = row.sonSonList
      }

    },

    // 拆解件数据
    setDisassembleData () {
      let flag = false
      let list = []
      this.disassembleProductList.forEach(item => {
        let time = item.hour + item.minute / 60
        if (item.name == '') {
          this.$message.error(`请填写拆解件名称`)
          flag = true
        }
        if (item.equipmentId == null || item.equipmentId == '') {
          this.$message.error(`请选择【${item.name}】的生产设备`)
          flag = true
        }
        if (item.schedulingNum == 0 || item.schedulingNum == null) {
          this.$message.error(`请填写【${item.name}】的排产数量`)
          flag = true
        }
        if (time == 0) {
          this.$message.error(`请填写【${item.name}】的预计完成时间`)
          flag = true
        }
      })
      if (flag) return
      this.productList.forEach(item => {
        this.disassembleProductList.forEach(d_item => {
          if (item.id == d_item.id) {
            let time = d_item.hour + d_item.minute / 60
            d_item.finishHour = time.toFixed(1)
            list.push({
              name: d_item.name,
              equipmentId: d_item.equipmentId,
              schedulingNum: d_item.schedulingNum,
              finishHour: time.toFixed(1)
            })
            item.sonSonList = list
          }

        })

      })

      this.innerVisible = false
      console.log(this.productList)
    },

    //选择产品
    handleSelection (list) {
      this.selectionList = list
      console.log(list)
    },
    // 排产数量改变
    changeNum (currentValue, item) {
      if (item.schedulingNum > (item.num - item.scheduledNum)) {
        item.schedulingNum = item.num - item.scheduledNum
        // this.$message.error(`【${data.name}】剩余数量不足，请重新填写排产数量`)
      }
    },
    async submmit () {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          if (this.selectionList.length == 0) {
            this.$message.error(`请选择产品排产`)
            return
          }
          let list = []
          let flag = false
          this.selectionList.map(item => {
            let time = item.hour + item.minute / 60
            list.push({
              produceId: item.produceId,
              productId: item.quotesProductId,
              schedulingNum: item.schedulingNum,
              equipmentId: item.equipmentId,
              finishHour: time.toFixed(2),
              isDismantle: item.sonSonList.length == 0 ? 0 : 1,//是否是拆解件 0否 1是
              sonSonList: item.sonSonList
            })
            if (item.equipmentId == null || item.equipmentId == '' && item.sonSonList.length == 0) {
              this.$message.error(`请选择【${item.name}】的生产设备`)
              flag = true
            }
            if (item.schedulingNum == 0 || item.schedulingNum == null) {
              this.$message.error(`请填写【${item.name}】的排产数量`)
              flag = true
            }
            // if (item.schedulingNum > (item.num - item.scheduledNum)) {
            //   this.$message.error(`【${item.name}】剩余数量不足，请重新填写排产数量`)
            //   flag = true
            // }
            if (time == 0 && item.sonSonList.length == 0) {
              this.$message.error(`请填写【${item.name}】的预计完成时间`)
              flag = true
            }
          })
          if (flag) return
          this.form.schedulingSonList = list
          console.log(this.form)
          this.isSaveing = true
          let res = await this.$API.produce.addProduction.post(this.form)
          this.isSaveing = false
          this.$refs.dialogForm.resetFields()
          if (res.code == 200) {
            this.$emit('success')
            this.visible = false
            this.$message.success("操作成功")
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.rowTime {
  display: flex;
  justify-content: space-around;
  align-items: center;
  p {
    margin: 0 3px;
  }
}
</style>